var QQMapWX = require('../../lib/qqmap-wx-jssdk');

const {
  getAllLandmarkApi,
  getRecordApi,
  getDistanceApi,
  getDisOrder
} = require("../../public/api");
const {
  baseURL
} = require("../../public/request");
var qqmapsdk;
Page({
  data: {
    targetLocation: [], //用户要去的地点
    result: [],
    bestLine: {},
    bestLineStr: "",
    steps: [],
    distanceList: [],
    distanceLateLocationList: [],
    show: false,
    mapCenter: {
      latitude: 31.248791,
      longitude: 120.573765
    },
    schoolCenter: {
      latitude: 31.248791,
      longitude: 120.573765
    },
    MyLocation: {
      latitude: 31.248791,
      longitude: 120.573765,
      id: 0
    },
    mapWidth: '',
    mapHeight: '',
    polygons: [{
      // 指定的不规则区域蓝线
      points: [{
          latitude: 31.253106,
          longitude: 120.571471
        },
        {
          latitude: 31.252344,
          longitude: 120.574531
        },
        {
          latitude: 31.252179,
          longitude: 120.577277
        },
        {
          latitude: 31.25222,
          longitude: 120.577927
        },
        {
          latitude: 31.252777,
          longitude: 120.580457
        },
        {
          latitude: 31.254609,
          longitude: 120.582649
        },
        {
          latitude: 31.253127,
          longitude: 120.58566
        },
        {
          latitude: 31.249667,
          longitude: 120.583588
        },
        {
          latitude: 31.248658,
          longitude: 120.582408
        },
        {
          latitude: 31.247443,
          longitude: 120.581806
        },
        {
          latitude: 31.246001,
          longitude: 120.580168
        },
        {
          latitude: 31.24528,
          longitude: 120.577686
        },
        {
          latitude: 31.24526,
          longitude: 120.568773
        },
        {
          latitude: 31.246207,
          longitude: 120.56793
        }
      ],
      strokeWidth: 2,
      strokeColor: 'rgba(43,131,218,0.87)'
      //,fillColor: 'rgba(7,96,243,0)'
    }],
    // 地图包含的区域
    points: [{
        latitude: 31.253106,
        longitude: 120.571471
      },
      {
        latitude: 31.252344,
        longitude: 120.574531
      },
      {
        latitude: 31.252179,
        longitude: 120.577277
      },
      {
        latitude: 31.25222,
        longitude: 120.577927
      },
      {
        latitude: 31.252777,
        longitude: 120.580457
      },
      {
        latitude: 31.254609,
        longitude: 120.582649
      },
      {
        latitude: 31.253127,
        longitude: 120.58566
      },
      {
        latitude: 31.249667,
        longitude: 120.583588
      },
      {
        latitude: 31.248658,
        longitude: 120.582408
      },
      {
        latitude: 31.247443,
        longitude: 120.581806
      },
      {
        latitude: 31.246001,
        longitude: 120.580168
      },
      {
        latitude: 31.24528,
        longitude: 120.577686
      },
      {
        latitude: 31.24526,
        longitude: 120.568773
      },
      {
        latitude: 31.246207,
        longitude: 120.56793
      },
      {
        latitude: 31.2427,
        longitude: 120.57452
      }
    ],
    markers: [],
    locations: [] //地标元数据
  },
  onChangeData(event) {
    console.log(event);
  },
  onChange(event) {
    console.log(event);
    this.setData({
      result: event.detail,
    });
  },
  onLoad: function () {
    const that = this
    getAllLandmarkApi().then(res => {
      const transformedData = res.data.data.map(item => ({
        ...item, // 复制原始对象的所有属性
        iconPath: `${baseURL}/common/download?name=${item.iconpath}` // 修改iconPath属性
      }));
      that.setData({
        markers: transformedData
      });
      that.setData({
        locations: transformedData
      });

    }).catch(err => {
      console.log('失败回调', err)
    })
    // 实例化API核心类
    qqmapsdk = '2K5BZ-753WZ-JAOX5-ZAIAX-LBC7J-E4F5D';
    // 调用接口
    var sy = wx.getSystemInfoSync(),
      mapWidth = sy.windowWidth * 2,
      mapHeight = sy.windowHeight * 2;
    this.mapWidth = mapWidth,
      this.mapHeight = mapHeight
  },
  onShow: function () {
    this.getLocation()
  },

  onMarkerTap(e) {
    wx.navigateTo({
      url: '/pages/locationsDetail/locationsDetail?id=' + e.detail.markerId
    })
  },


  getLocation() {
    const _this = this
    console.log(_this.data.MyLocation);
    console.log(_this.data.markers);
    const location = {
      latitude: "",
      longitude: "",
      height: 60,
      width: 60,
      iconpath: "../../assets/images/my-selected.png",
      id: 0,
      label: {
        color: "#000000",
        content: "我的位置",
        fontsize: 12,
        textalign: "center"
      }
    }
    wx.getLocation({
      // 高精度
      isHighAccuracy: true,
      success(res) {
        console.log(res);
        //地图中点设为定位点
        _this.setData({
          mapCenter: {
            latitude: res.latitude,
            longitude: res.longitude
          }
        })
        location.latitude = res.latitude
        location.longitude = res.longitude
        const locations = _this.data.markers
        locations.push(location)

        //定位点添加到地标中
        _this.setData({
          markers: locations
        })
        _this.setData({
          MyLocation: location
        })

        console.log(MyLocation);

      }
    })
  },
  creatline() {

    let res = this.filterByIds(this.data.markers, this.data.result)
    console.log(res);
    this.calculateDistances(res)
  },
  intelligentPlanning() {
    //
    this.showPopup()
  },
  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  calculateDistances(targetLocarion) {
    console.log('calculateDistances');
    const _this = this;
    const distanceList = [];
    try {
      // 获取所有地点的坐标 
      //const placeData = _this.data.locations;
      const placeData = targetLocarion
      const promises = [];
      // 计算地点之间的距离
      for (let i = 0; i < placeData.length; i++) {
        for (let j = i + 1; j < placeData.length; j++) {
          promises.push(_this.calculateDistance(placeData[i], placeData[j], distanceList));
        }
      }
      // 等待所有异步操作完成
      Promise.all(promises)
        .then(() => {
          console.log(distanceList);
          _this.setData({
            distanceList: distanceList
          });
          _this.calculateLocationDistances(targetLocarion)
        })
        .catch(error => {
          console.error("Error:", error);
        });
    } catch (error) {
      console.error("Error:", error);
    }
  },
  calculateLocationDistances(targetLocarion) {
    const _this = this;

    const distanceLateLocationList = [];
    try {
      // 获取所有地点的坐标 
      //const placeData = _this.data.locations;
      const placeData = targetLocarion
      const promises = [];
      //坐标与定位计算
      for (let i = 0; i < placeData.length; i++) {
        promises.push(_this.calculateDistance(placeData[i], _this.data.MyLocation, distanceLateLocationList));
      }
      // 等待所有异步操作完成
      Promise.all(promises)
        .then(() => {
          console.log(distanceLateLocationList);
          _this.setData({
            distanceLateLocationList: distanceLateLocationList
          })
          _this.showLine()
        })
        .catch(error => {
          console.error("Error:", error);
        });
    } catch (error) {
      console.error("Error:", error);
    }
  },
  async calculateDistance(placeA, placeB, list) {
    try {
      const res = await getDistanceApi({
        from: placeA,
        to: placeB,
        key: qqmapsdk,
      });
      console.log(res);
       //const distance = res.data.result.routes[0].distance;
      const distance = res  
      list.push({
        from: placeA.id,
        to: placeB.id,
        distance: distance
      });
      // 每次请求后延迟 200 毫秒
       await this.delay(200);
    } catch (error) {
      console.error(error);
    }
  },
  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  },
  showLine() {
    const line = getDisOrder(this.data.distanceList, this.data.distanceLateLocationList)
    const _this = this
    const result = _this.generatePathDisplay(_this.data.markers, line.path)
    console.log(result);
    this.setData({
      steps: result
    })
  },

  filterByIds(array, idArray) {

    let res = array.filter(item => idArray.includes(item.id.toString()));

    return res;
  },
  generatePathDisplay(dataArray, idArray) {
    // 创建一个映射，方便根据id快速查找对应的label  
    const idToLabelMap = new Map();
    for (const item of dataArray) {
      idToLabelMap.set(item.id, item.label.content);
    }
    // 初始化结果数组  
    const result = [];

    // 遍历id数组，查找对应的label并添加到结果数组  

    result.push({
      text: '当前位置', // 根据结果数组的长度确定目的地编号  
      desc: "",
    });
    for (const id of idArray) {
      const label = idToLabelMap.get(id);
      if (label) {
        result.push({
          text: '目的地' + (result.length), // 根据结果数组的长度确定目的地编号  
          desc: label,
        });
      }
    }

    return result;



    // // 创建一个映射，以便快速根据id查找对应的label内容  
    // const idToLabelMap = new Map(dataArray.map(item => [item.id, item.label.content]));
    // // 遍历路径数组，查找对应的label内容并拼接  
    // const pathDisplay = pathArray.map(id => idToLabelMap.get(id)).join('->');
    // console.log(pathDisplay);
    // return pathDisplay;
  }

})